package NagrywarkaObrazkow;

import java.awt.AWTException;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import java.awt.MouseInfo;
import java.awt.PointerInfo;
import java.awt.Rectangle;
import java.awt.Robot;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner.DateEditor;
import javax.swing.Timer;

import java.awt.BorderLayout;

import javax.swing.BoxLayout;

import AAInicjalizacja.init.Init_AREAS;
import GUI.iOknoCzlapak;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Vector;

import javax.swing.JLayeredPane;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;

import java.awt.CardLayout;
import java.awt.Window.Type;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JSpinner;
import javax.swing.SwingConstants;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.SpinnerNumberModel;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
import org.jnativehook.mouse.NativeMouseListener;
import org.jnativehook.mouse.NativeMouseMotionListener;
import org.jnativehook.mouse.NativeMouseWheelEvent;
import org.jnativehook.mouse.NativeMouseWheelListener;

import java.awt.Component;

import javax.swing.Box;

import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTextArea;


public class iNagrywarkaOkno extends iProgramRecorderObrazow 
			implements  ActionListener, ItemListener, NativeKeyListener, 
							NativeMouseInputListener,NativeMouseWheelListener, WindowListener {
		
	private static final long serialVersionUID = 1L;
		
	public JFrame frmNagrywarka;
	private JPanel iRamka_obraz;
	private JPanel iObraz;
	private JLayeredPane panel;
	private JPanel iP_Obraz;
	private JPanel panel_1;
	private JButton btnStart;
	private JButton btnPlay;
	private JButton btnStop;
	private JButton btnNewButton;
	private JButton btnNewButton_1;
	private JPanel iParm1; //parametry szerokos pobieranego obrazka
	
	private JSpinner iWysokoscOb;
	private JSpinner iSzerokoscOb;
	private JSpinner iProbki;

	private Robot rob;
	private BufferedImage iBuf; // zrzut spod kursorap
	private Image scaledImage;
	private Timer timer; //czestotliwosc probek
	private Path path;
	
	
	public JTextArea log;
	
	//boolean flaga1 = true; 	//true mokno jezdzi za kursorem, mozna zmieniac parametry
							// false okno stoi na wybranym elemencie
	//boolean flaga2 = true;	//onko nie porusza sie
	
	
	
	
	/**
	 * Create the application.
	 */
	public iNagrywarkaOkno() {
		super();
		
		initialize();
		
		try {
			GlobalScreen.registerNativeHook();
		} catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
            System.exit(1);
		}
		
		System.out.println("Hook state: "+ GlobalScreen.isNativeHookRegistered());

		GlobalScreen.getInstance().addNativeKeyListener(this);
		
		try {
			rob = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}

		try {
			String path = new java.io.File("..").getCanonicalPath();
				System.out.println("PATH \n" + path);
			//this.buf = ImageIO.read(new File(path+"/002-DoFi/src/NagrywarkaObrazkow/iKatObraz/centerConf.bmp"));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		
		frmNagrywarka = new JFrame();
		frmNagrywarka.setResizable(false);
		frmNagrywarka.setAlwaysOnTop(true);

		frmNagrywarka.setType(Type.UTILITY);
		frmNagrywarka.setTitle("Nagrywarka");
		frmNagrywarka.setBounds(100, 100, 370, 394);
		frmNagrywarka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		iP_Obraz = new iObraz();
		frmNagrywarka.getContentPane().setLayout(null);
		
		iRamka_obraz = new JPanel();
		iRamka_obraz.setBounds(5, 6, 156, 156);
		frmNagrywarka.getContentPane().add(iRamka_obraz);
		iRamka_obraz.setBorder(new MatteBorder(3, 3, 3, 3, (Color) new Color(0, 0, 0)));
		iRamka_obraz.setBackground(Color.DARK_GRAY);
		iRamka_obraz.setLayout(null);
		iRamka_obraz.add(iP_Obraz);
		
		panel_1 = new JPanel();
		panel_1.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				System.out.println(e.getKeyChar());

			}
		});
		
		iParm1 = new JPanel();
		iParm1.setBounds(5, 174, 156, 87);
		frmNagrywarka.getContentPane().add(iParm1);
		iParm1.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		iParm1.setLayout(new GridLayout(0, 3, 0, 0));
		
		
		iSzerokoscOb = new JSpinner();
		iSzerokoscOb.setToolTipText("Szeroko\u015B\u0107 pr\u00F3bki 1-301px");
		iSzerokoscOb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				iWysokoscOb.setValue((long) iSzerokoscOb.getValue());
			}
		});
		
		horizontalStrut_1 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_1);
		iSzerokoscOb.setModel(new SpinnerNumberModel(new Long(7), new Long(1), new Long(301), new Long(10)));
		iParm1.add(iSzerokoscOb);
		
		
		iWysokoscOb = new JSpinner();
		iWysokoscOb.setToolTipText("Wysoko\u015B\u0107 pr\u00F3bki 1-301px");
		iWysokoscOb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				iSzerokoscOb.setValue((long) iWysokoscOb.getValue());
			}
		});
		
		JLabel lblSzer_1 = new JLabel("szer.");
		lblSzer_1.setHorizontalAlignment(SwingConstants.CENTER);
		lblSzer_1.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblSzer_1);
		
		Component horizontalStrut_2 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_2);
		iWysokoscOb.setModel(new SpinnerNumberModel(new Long(7), new Long(1), new Long(301), new Long(10)));
		iWysokoscOb.setFont(new Font("Tahoma", Font.BOLD, 11));
		iParm1.add(iWysokoscOb);
		
		JLabel lblWys = new JLabel("wys.");
		lblWys.setHorizontalAlignment(SwingConstants.CENTER);
		lblWys.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblWys);
		
		Component horizontalStrut_3 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_3);
		
		iProbki = new JSpinner();
		iProbki.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				timer.setDelay((int)iProbki.getValue());
			}
		});
		iProbki.setModel(new SpinnerNumberModel(new Integer(10), new Integer(10), new Integer(500), new Integer(10)));
		iProbki.setToolTipText("Szybko\u015B\u0107 probki obrazu 10-500ms");
		iParm1.add(iProbki);
		
		JLabel lblms = new JLabel("ms");
		lblms.setHorizontalAlignment(SwingConstants.CENTER);
		lblms.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblms);
		panel_1.setBounds(5, 262, 156, 95);
		frmNagrywarka.getContentPane().add(panel_1);
		panel_1.setLayout(new GridLayout(0, 2, 0, 0));
		
		btnStart = new JButton("Start");
		btnStart.setEnabled(true);
		btnStart.setToolTipText("Naci\u015Bnij \"S\" zablokujesz ramk\u0119 podgladu");
		panel_1.add(btnStart);
		
		btnStop = new JButton("Stop");
		btnStop.setEnabled(false);
		btnStop.setToolTipText("Naci\u015Bnij \"S\" odblokujesz ramk\u0119 podgladu");
		panel_1.add(btnStop);
		
		btnPlay = new JButton("Nagraj");
		btnPlay.setEnabled(true);
		btnPlay.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				if (btnStart.isEnabled()){
					JOptionPane.showMessageDialog(
							null, "Nie jest zastopowana klatka\n NACISNIJ KLAWIS <S>");
					return;
				} else if (btnPlay.isEnabled()) btnPlay.setEnabled(false); 
				else btnPlay.setEnabled(true);
				
			}
		});
		btnPlay.setToolTipText("Naci\u015Bnij \"S\" odblokujesz ramk\u0119 podgladu");
		panel_1.add(btnPlay);
		
		Component horizontalStrut = Box.createHorizontalStrut(20);
		panel_1.add(horizontalStrut);
		
		btnNewButton = new JButton("sortuj");
		panel_1.add(btnNewButton);
		
		btnNewButton_1 = new JButton("zapisz");
		btnNewButton_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent arg0) {
				try {
					iZapisz();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		panel_1.add(btnNewButton_1);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(171, 6, 183, 156);
		frmNagrywarka.getContentPane().add(panel_2);
		panel_2.setLayout(new GridLayout(0, 1, 0, 0));
		
		log = new JTextArea();
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
		panel_2.add(log);
        JScrollPane logScrollPane = new JScrollPane(log);
        panel_2.add(logScrollPane);

				
		timer = new Timer(20, action);
		timer.start();
		
		frmNagrywarka.setVisible(true);

	}
	int a = 0, b=0, sz=0, w=0;
	private ActionListener action = new ActionListener() {
		public void actionPerformed(ActionEvent ae) {
			//System.out.println("starat");
			if(btnStart.isEnabled()){
				a = igetCurrentPosX();
				b = igetCurrentPosY();
				sz = (int)(long)iSzerokoscOb.getValue();
				w  = (int)(long)iWysokoscOb.getValue();
				
			}
			iBuf = rob.createScreenCapture(new Rectangle (a-sz/2-40, b-w/2-40, sz, w));
			if (!btnPlay.isEnabled()) iIN (iBuf);
			else
				try {
					iSortuj();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			//panel_1.revalidate();
			iRamka_obraz.repaint();
		}
	};
	private Component horizontalStrut_1;
	//============================================================================
	private int igetCurrentPosX(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.print("POZYCJA MOUSA X: " + pointer.getLocation().x + " ");
		return pointer.getLocation().x;
	}
	private int igetCurrentPosY(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.println("POZYCJA MOUSA Y: " + pointer.getLocation().y);
		return pointer.getLocation().y;
	}
	

	class iObraz extends JPanel {
		//private Image img = null;
		int wFrameObraz;
		int hFrameObraz;
		
		public iObraz() {
			super();
	
			setBackground(Color.gray);
			setBounds(new Rectangle(10, 11, 136, 134));
			setBorder(BorderFactory.createLineBorder(Color.black));
			setLayout(new FlowLayout(FlowLayout.CENTER)); 
		}
		
		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
	
			wFrameObraz = iP_Obraz.getSize().width;
			hFrameObraz = iP_Obraz.getSize().height;
			if ( iBuf !=  null ){
				scaledImage = (iBuf.getScaledInstance(wFrameObraz, wFrameObraz, (Image.SCALE_AREA_AVERAGING)));
				g.drawImage(scaledImage, 0, 0, null);
			}
		}
	}
			
		@Override
		public void windowOpened(WindowEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void windowClosing(WindowEvent e) {
			System.out.println("zmaykasz okno)");		
		}
		
		@Override
		public void windowClosed(WindowEvent e) {
			//Clean up the native hook.
			GlobalScreen.unregisterNativeHook();
			System.runFinalization();
			System.exit(0);
		}
		
		@Override
		public void windowIconified(WindowEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void windowDeiconified(WindowEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void windowActivated(WindowEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void windowDeactivated(WindowEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void nativeKeyPressed(NativeKeyEvent arg0) {
				int a=arg0.getKeyCode();

				switch (a){
					case (KeyEvent.VK_P): 
						if (btnPlay.isEnabled()) btnPlay.setEnabled(false); else btnPlay.setEnabled(true);
						break;
					case (KeyEvent.VK_S):
						if (btnStart.isEnabled()) {
							btnStart.setEnabled(false); 
							btnStop.setEnabled(true); 
							}else {
							btnStart.setEnabled(true);
							btnStop.setEnabled(false);
						}
						break;
					case KeyEvent.VK_UP: 
						if ((long)iWysokoscOb.getValue()<301 && ((long)iWysokoscOb.getValue())>=12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+2);
						if ((long)iWysokoscOb.getValue()<301 && ((long)iWysokoscOb.getValue())<12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+2);
						break;
					case KeyEvent.VK_DOWN: 
						if ((long)iWysokoscOb.getValue()> 1 && ((long)iWysokoscOb.getValue())>=12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						if ((long)iWysokoscOb.getValue()> 1 && ((long)iWysokoscOb.getValue())< 12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						break;
					case KeyEvent.VK_LEFT: 
						if ((long)iWysokoscOb.getValue()> 1 && ((long)iWysokoscOb.getValue())>=12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						if ((long)iWysokoscOb.getValue()> 1 && ((long)iWysokoscOb.getValue())< 12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						break;
					case KeyEvent.VK_RIGHT: 
						if ((long)iWysokoscOb.getValue()<301 && ((long)iWysokoscOb.getValue())>=12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+2);
						if ((long)iWysokoscOb.getValue()<301 && ((long)iWysokoscOb.getValue())<12) iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+2);
						break;	
					case KeyEvent.VK_ESCAPE: 
						GlobalScreen.unregisterNativeHook();
						System.runFinalization();
						System.exit(2);
						break;
				}
		}
		
		@Override
		public void nativeKeyReleased(NativeKeyEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void nativeKeyTyped(NativeKeyEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void nativeMouseClicked(NativeMouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void nativeMousePressed(NativeMouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void nativeMouseReleased(NativeMouseEvent arg0) {
			
		}
		
		@Override
		public void nativeMouseDragged(NativeMouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void nativeMouseMoved(NativeMouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void nativeMouseWheelMoved(NativeMouseWheelEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void itemStateChanged(ItemEvent e) {
			// TODO Auto-generated method stub
			
		}
		

		@Override
		public void iLog(String log) {
			this.log.append(""+log +"\n");
		}
		

		/**
		 * Launch the application.
		 */
		public static void main(String[] args) {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					try {
						iNagrywarkaOkno window = new iNagrywarkaOkno();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
}
